﻿using Microsoft.Extensions.Logging;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using TcpJsonService.Core;

namespace TcpJsonService.Fvs
{
    /// <summary>
    /// 模拟雾灯通道
    /// </summary>
    public class VirtualControllerChannel_New : TcpChannel
    {
        /// <summary>
        /// 控制器编号
        /// </summary>
        private readonly int _controllerId;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="remoteEndPoint">远程地址</param>
        /// <param name="logger">日志</param>
        /// <param name="controllerId">控制器编号</param>
        public VirtualControllerChannel_New(IPEndPoint remoteEndPoint, ILogger logger, int controllerId)
            : base(remoteEndPoint, logger)
        {
            _controllerId = controllerId;
        }

        protected override bool Unpack(Socket socket, List<byte> buffer, ref int offset)
        {
            if (buffer.Count < 6 || buffer[0] != 0x8A || buffer[1] != 0x99 || buffer[buffer.Count - 1] != 0xff)
            {
                _logger.LogWarning($"lamp protocol format error {ByteConvert.ToHex(buffer)}");
            }
            else
            {
                int protocolId = buffer[4];
                if (protocolId == 0x11)
                {
                    byte[] responseBuffer = [0x99, 0x8A, Convert.ToByte(_controllerId), 0x00, Convert.ToByte(protocolId), 0xff];
                    Send(socket, responseBuffer);
                }
                else if (protocolId == 0x0b)
                {
                    byte[] responseBuffer = [0x99,
                        0x8A,
                        Convert.ToByte(_controllerId),
                        0x00,
                        Convert.ToByte(protocolId),
                        0x06,
                        0x07,
                        0x08,
                        0x09,
                        0x0A,
                        0x0B,
                        0x0C,
                        0x0D,
                        0x0E,
                        0x0F,
                        0x10,
                        0x11,
                        0x12,
                        0x13,
                        0xff];
                    Send(socket, responseBuffer);
                }
            }
            offset += buffer.Count;
            return true;
        }
    }
}
